/* Filter.java
 *
 * Author:	Malcolm Staudacher
 * Date:	Oct 5, 2008
 *
 */

package itb.fhv.sa.pipesfilters;

public abstract class Filter extends PLElement implements Runnable {

	protected boolean m_active;


	public Filter() {
		m_neighbour2 = null;
		m_active = false;
	}


	public Filter(Pipe neighbour) {
		m_neighbour1 = neighbour;
		m_neighbour2 = null;
		m_active = false;
	}


	/**
	 * Sets this filter to be an active filter.
	 * 
	 * @param neighbour2
	 *            The second neighbour of this filter, since an active filter
	 *            needs to know both of its neighbours in the pipeline.
	 */
	public void setActive(Pipe neighbour2) {
		m_active = true;
		m_neighbour2 = neighbour2;
	}


	@Override
	protected abstract void flush();


	@Override
	public abstract PLOutput read();


	@Override
	public abstract boolean write(PLOutput plo);


	/**
	 * Starts a new thread (to be used, if this is an active filter). The new
	 * thread pulls data from the pipeline and writes it to the next pipeline
	 * element.
	 */
	public void run() {
		boolean written = false;

		System.out.println("Active Filter thread running");

		PLOutput plo = read();

		while (!plo.getContent().contains("\1")) {

			written = m_neighbour2.write(plo);

			if (written == true) {
				plo = read();
				written = false;
			}

		}

		// write last word
		while (written == false) {
			written = m_neighbour2.write(plo);
		}

		m_neighbour2.flush();
	}

}
